package com.qijian.maindata.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qijian.common.annotation.Log;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.page.TableDataInfo;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.maindata.domain.InspectionScheme;
import com.qijian.maindata.domain.query.InspectionSchemeQuery;
import com.qijian.maindata.domain.vo.InspectionSchemeVo;
import com.qijian.maindata.domain.vo.UpdateItemStorageRequestVo;
import com.qijian.maindata.service.IInspectionSchemeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * 检验方案-新Controller
 *
 * @author qijian
 * @date 2024-02-02
 */
@Api(tags = "检验方案-新")
@RestController
@RequiredArgsConstructor
@RequestMapping("/maindata/inspectionScheme")
public class InspectionSchemeController extends BaseController {

    private final IInspectionSchemeService inspectionSchemeService;

    /**
     * 查询检验方案-新列表
     */
    @PreAuthorize("@ss.hasPermi('maindata:scheme:list')")
    @GetMapping("/list")
    public TableDataInfo list(InspectionSchemeQuery query, Page<InspectionScheme> page) {
        QueryWrapper<InspectionScheme> queryWrapper = WhereEntityTool.invoke(query);
        queryWrapper.orderByDesc("update_time");
        return getDataTable(inspectionSchemeService.page(page, queryWrapper));
    }


    /***
     * 根据(检验类型,bomId,检验班组),获取检验项及明细,供检验报告录入时选择
     * 7.30 去掉检验班组的限制
     * @return
     */
    @GetMapping("/listDialog")
    public TableDataInfo listDialog(InspectionSchemeQuery query, Page<InspectionScheme> page){
        /*if(Objects.isNull(query.getBomId()) || StrUtil.isBlank(query.getInspectionType())){
            return getDataTable(new Page<>(page.getCurrent(),page.getSize(),0));
        }*/
        if(StrUtil.isBlank(query.getInspectionType())){
            return getDataTable(new Page<>(page.getCurrent(),page.getSize(),0));
        }
        initOrderItem(InspectionScheme.class, page.orders());
        Page<InspectionScheme> pageResult = inspectionSchemeService.page(page, WhereEntityTool.invoke(query));
        if(CollUtil.isNotEmpty(pageResult.getRecords())){
            pageResult.getRecords().forEach(p->{
                InspectionSchemeVo info = inspectionSchemeService.getInfo(p.getId());
                if(Objects.nonNull(info)){
                    p.setItems(info.getDetailsVoList());
                }
            });
        }
        return getDataTable(pageResult);
    }

    /**
     * 获取检验方案-新详细信息
     */
    @PreAuthorize("@ss.hasAnyPermi('maindata:scheme:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(inspectionSchemeService.getInfo(id));
    }

    /**
     * 新增检验方案-新
     */
    @PreAuthorize("@ss.hasPermi('maindata:scheme:add')")
    @Log(title = "检验方案-新" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InspectionSchemeVo inspectionSchemeVo) {
        return toAjax(inspectionSchemeService.saveVo(inspectionSchemeVo));
    }

    /**
     * 修改检验方案-新
     */
    @PreAuthorize("@ss.hasPermi('maindata:scheme:edit')")
    @Log(title = "检验方案-新" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InspectionSchemeVo inspectionSchemeVo) {
        return toAjax(inspectionSchemeService.saveVo(inspectionSchemeVo));
    }

    /**
     * 删除检验方案-新
     */
    @PreAuthorize("@ss.hasPermi('maindata:scheme:remove')")
    @Log(title = "检验方案-新" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(inspectionSchemeService.remove(new LambdaQueryWrapper<InspectionScheme>()
                .in(InspectionScheme::getId,ids)));
    }


    @PreAuthorize("@ss.hasPermi('maindata:scheme:export')")
    @Log(title = "检验方案-新-模板导出", businessType = BusinessType.EXPORT)
    @ApiOperation("检验方案新模版导出")
    @GetMapping("/export/template")
    public AjaxResult exportTemplate(HttpServletResponse response) throws Exception{
        return inspectionSchemeService.exportTemplate(response);
    }

    @PreAuthorize("@ss.hasPermi('maindata:scheme:add')")
    @Log(title = "检验方案导入-校验", businessType = BusinessType.IMPORT)
    @PostMapping("/importCheck")
    @ApiOperation("导入检验方案-校验")
    public AjaxResult importExcelCheck(MultipartFile file) throws Exception{
        return inspectionSchemeService.doImportCheck(file);
    }

    @PreAuthorize("@ss.hasPermi('maindata:scheme:add')")
    @Log(title = "检验方案导入-新", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    @ApiOperation("导入检验方案-新")
    public void importExcel(MultipartFile file) throws Exception{
        inspectionSchemeService.doImport(file);
    }

    /***
     * 上传图片压缩zip包
     * @param file
     * @return
     */
    @PostMapping("/unzip")
    public AjaxResult unzip(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "schemeId") Long schemeId) {
        return toAjax(inspectionSchemeService.importZip(schemeId,file));
    }

    /***
     * 上传图片压缩zip包检验文件是否存在
     * @param file
     * @return
     */
    @PostMapping("/unzipCheck")
    public AjaxResult unzipCheck(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "schemeId") Long schemeId) {
        return inspectionSchemeService.importZipCheck(schemeId,file);
    }

    /***
     * 更新附件信息
     * @param request
     * @return
     */
    @PostMapping("/updateStorage")
    public AjaxResult updateItemStorage(@RequestBody UpdateItemStorageRequestVo request){
        return toAjax(inspectionSchemeService.updateItemStorage(request));
    }

    //刷新默认方案
    @GetMapping("/refresh")
    public AjaxResult refreshInspection(){
        return AjaxResult.success(inspectionSchemeService.refreshInspection());
    }

    /***
     * 根据(开工令，报验类型),获取检验项及明细,供外协报验选取
     * @return
     */
    @GetMapping("/listDialogForOut")
    public TableDataInfo listDialogForOut(InspectionSchemeQuery query, Page<InspectionScheme> page){
        if(StrUtil.isBlank(query.getInspectionType())||CollUtil.isEmpty(query.getProjectIds())){
            return getDataTable(new Page<>(page.getCurrent(),page.getSize(),0));
        }
        initOrderItem(InspectionScheme.class, page.orders());
        Page<InspectionSchemeVo> pageResult = inspectionSchemeService.pageForOutInspection(page, WhereEntityTool.invoke(query));
        if(CollUtil.isNotEmpty(pageResult.getRecords())){
            pageResult.getRecords().forEach(p->{
                InspectionSchemeVo info = inspectionSchemeService.getInfo(p.getId());
                if(Objects.nonNull(info)){
                    p.setItems(info.getDetailsVoList());
                }
            });
        }
        return getDataTable(pageResult);
    }
}
